// pages/xzMap/xzMap.js
const app = getApp()
import {
  urls
} from '../../api/urls'

import {
  property_list_check,
  property_opened
} from '../../api/request'

var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
qqmapsdk = new QQMapWX({
  key: urls.qqmap_wx_jssdkKey
});
Page({
  /**
   * 页面的初始数据
   */
  data: {
    open_property: [], //已开通小区
    start_pos: '', //起始经纬度
    currentIndex: 0,
    vanLoading: true,
    search_onFocus: false,
    value: '',
    address: [],
    new_address_list: [], //后台查证后返回的小区名称
    latitude: 29.5635211047864,
    longitude: 106.54876876857185,
    scale: 13, //缩放倍数
    covers: [],
    markers: [],
    controls: [{
        id: 1,
        iconPath: '/images/jian.png',
        position: {
          left: 40,
          top: 20,
          width: 20,
          height: 20
        },
        clickable: true
      },
      {
        id: 2,
        iconPath: '/images/jia.png',
        position: {
          left: 10,
          top: 20,
          width: 20,
          height: 20
        },
        clickable: true
      },
      { //中心点定位
        id: 3,
        iconPath: '/images/location.png',
        position: {
          left: wx.getSystemInfoSync().windowWidth / 2 - 25,
          top: wx.getSystemInfoSync().windowWidth / 2 - 25,
          width: 50,
          height: 50,
          title: "切换小区"
        },
        clickable: true
      },

      { //切换为我的小区
        id: 4,
        iconPath: '/images/my_property.png',
        position: {
          left: wx.getSystemInfoSync().windowWidth / 2 - 40,
          top: wx.getSystemInfoSync().windowWidth / 2 - 25 - 20,
          width: 80,
          height: 20,
          title: "我的小区"
        },
        clickable: true
      },

    ],

  },

  property_open() {
    let that = this

    this.setData({
      search_onFocus: true
    })

    var data = {
      para: [app.globalData.cur_my_openid, app.globalData.cur_property_code]
    }
    property_opened(data).then(res => {
      that.setData({
        open_property: res.data,
      })
    })
  },


  //点击merkers
  markertap(e) {
    //    console.log('------markerId=', e.markerId)

    wx.showActionSheet({
      itemList: ["A"],
      success: function (res) {
        //        console.log(res.tapIndex)
      },
      fail: function (res) {
        //        console.log(res.errMsg)
      }
    })
  },

  //点击缩放按钮动态请求数据
  controltap(e) {
    var that = this;
    //    console.log("scale===" + this.data.scale)
    //缩小
    if (e.controlId == 1) {
      that.setData({
        scale: --this.data.scale
      })
    }
    //放大
    if (e.controlId == 2) {
      that.setData({
        scale: ++this.data.scale
      })
    }
    //获取中心点
    if (e.controlId == 3 || e.controlId == 4) {
      that.map_set_center()
    }
  },

  map_set_center() {
    let that = this
    var mapCtx = wx.createMapContext("myMap");
    mapCtx.getCenterLocation({
      success: function (res) {
        if (res.latitude.toFixed(4) != that.data.latitude.toFixed(4) || res.longitude.toFixed(4) != that.data.longitude.toFixed(4)) {
          //位置变化
          //         console.log('-----center pos=', res)
          //重新定位
          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            start_pos: res.latitude + ',' + res.longitude,
            circles: [{
              latitude: res.latitude,
              longitude: res.longitude,
              color: '#FF0000DD',
              fillColor: '#d5cef430',
              radius: 3000, //半径3000米
              strokeWidth: 1
            }],
          })
          //刷新附近新的小区列表
          that.reverseGeocoder(res.latitude + ',' + res.longitude)
        }
      }
    })
  },

  onChange(e) {
    let that = this
    var value = e.detail
    value != '' ? this.setData({
      vanLoading: true
    }) : ''
    this.Search_By_Address(value, this.data.start_pos)
  },

  //根据经纬度推荐附近信息
  Suggestion_By_Adress(value, m_location) {
    var that = this;
    //    var m_location = that.latitude + ',' + that.longitude;
    qqmapsdk.getSuggestion({
      keyword: value,
      location: m_location,
      //参考：http://lbs.qq.com/webservice_v1/guide-suggestion.html
      //http://lbs.qq.com/service/webService/webServiceGuide/webServiceAppendix
      filter: 'category=房产小区:住宅区:住宅小区',
      region_fix: '0', //允许扩大到其它城市
      region: '全国',
      policy: '1',

      success: (res) => {
        let data_list = res.data
        //-----------map title list begin------------


        var property_name_str = ''
        var pos_xy_group = ''
        data_list.forEach(item => {
          var val = item.location
          pos_xy_group == '' ?
            pos_xy_group = val.lat + ',' + val.lng :
            pos_xy_group = pos_xy_group + ';' + val.lat + ',' + val.lng;

          if (property_name_str == '') {
            property_name_str = item.title;
          } else {
            property_name_str = property_name_str + ',' + item.title;
          }
        })

        var data = {
          para: [property_name_str]
        }
        property_list_check(data).then(res => {
          that.setData({
            new_address_list: res.data,
          })
        })
        //-----------map title list end------------
        that.setData({
          address: data_list,
          vanLoading: false
        })
        that.calculateDistance(this.data.start_pos, pos_xy_group)
      }
    })
  },

  //地点搜索
  Search_By_Address(value, m_pos) {
    var _this = this;
    var that = this;
    //参考http://lbs.qq.com/service/webService/webServiceGuide/webServiceSearch
    qqmapsdk.search({
      keyword: value, //搜索关键词
      location: m_pos, //设置周边搜索中心点
      //why filter error?      
      //  filter: 'category=房产小区:住宅区:住宅小区',

      success: (res) => {
        let data_list = res.data
        if (data_list.length == 0) return that.setData({
          vanLoading: false
        })
        //-----------map title list begin------------
        //将第一个小区默认定位为地图的中心点
        that.setData({
          latitude: data_list[0].location.lat,
          longitude: data_list[0].location.lng,
        })


        var property_name_str = ''
        var pos_xy_group = ''
        data_list.forEach(item => {
          var val = item.location
          pos_xy_group == '' ?
            pos_xy_group = val.lat + ',' + val.lng :
            pos_xy_group = pos_xy_group + ';' + val.lat + ',' + val.lng;

          if (property_name_str == '') {
            property_name_str = item.title;
          } else {
            property_name_str = property_name_str + ',' + item.title;
          }
        })

        var data = {
          para: [property_name_str]
        }
        property_list_check(data).then(res => {
          that.setData({
            new_address_list: res.data,
          })
        })
        //-----------map title list end------------


        that.setData({
          address: data_list,
          vanLoading: false
        })
        that.calculateDistance(this.data.start_pos, pos_xy_group)
      },

      fail: function (res) {},

      complete: function (res) {}
    });
  },
  //经纬度换中文地址
  reverseGeocoder(pos_xy) {
    var _this = this;
    //    console.log('---------pos_xy', pos_xy)
    qqmapsdk.reverseGeocoder({
      //位置坐标，默认获取当前位置，非必须参数
      location: pos_xy || '', //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
      success: function (res) { //成功后的回调
        var address = res.result.address_component.city + res.result.address_component.district

        //        console.log('---2---当前位置=' + res.result.address);
        _this.Suggestion_By_Adress('小区', pos_xy)
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },

  //已开通物业小区选择
  opened_select(e) {
    var m_property_code = e.currentTarget.dataset.property_code
    wx.setStorageSync('switch_code', m_property_code) //切换新小区 临时标记

    wx.switchTab({
      url: '/pages/home/index',
      success(res) {
        let page = getCurrentPages().pop();
        if (page == undefined || page == null) {
          return
        }
        page.onLoad(); //重新刷新主页面
      }
    })
  },




  //物业小区选择
  property_select(e) {
    var m_latitude = e.currentTarget.dataset.item.lat
    var m_longitude = e.currentTarget.dataset.item.lng
    var m_currentIndex = e.currentTarget.dataset.index
    this.setData({
      latitude: m_latitude,
      longitude: m_longitude,
      currentIndex: m_currentIndex,
    })
    if (this.data.new_address_list[m_currentIndex].PROPERTY_CODE != null) {
      wx.setStorageSync('switch_code', this.data.new_address_list[m_currentIndex].PROPERTY_CODE) //切换新小区 临时标记

      wx.switchTab({
        url: '/pages/home/index',
        success(res) {
          let page = getCurrentPages().pop();
          if (page == undefined || page == null) {
            return
          }
          page.onLoad(); //重新刷新主页面
        }
      })
    } else {
      wx.setStorageSync('PROPERTY_ADDRESS', this.data.address[m_currentIndex])
      wx.navigateTo({
        url: '/pages/xzMap/new_property',
      })

    }
  },

  //输入框聚焦
  onFocus() {
    this.setData({
      search_onFocus: true
    })
  },
  onBlur() {},
  //取消
  onCancel() {
    this.setData({
      search_onFocus: false
    })
  },

  arrow_down() {
    this.setData({
      search_onFocus: false
    })
  },

  //获取当前位置
  getSetting() {
    var _this = this
    wx.getSetting({
      success: (res) => { //授权成功
        wx.getLocation({ //获取当前位置经纬度
          type: 'gcj02',
          success: (res) => {
            //            console.log('---1---getLocation=', res)
            _this.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              start_pos: res.latitude + ',' + res.longitude,
              circles: [{
                latitude: res.latitude,
                longitude: res.longitude,
                color: '#FF0000DD',
                fillColor: '#d5cef430',
                radius: 3000, //半径3000米
                strokeWidth: 1
              }],
            })
            this.reverseGeocoder(_this.data.latitude + ',' + _this.data.longitude)

          }
        })
      }
    })
  },

  onShow: function () {
    this.getSetting()
  },

  // 距离计算
  calculateDistance(start, dest) {
    var _this = this;
    //调用距离计算接口
    qqmapsdk.calculateDistance({
      //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
      //from参数不填默认当前地址
      //获取表单提交的经纬度并设置from和to参数（示例为string格式）
      from: start || '', //若起点有数据则采用起点坐标，若为空默认当前地址
      to: dest, //终点坐标
      success: function (res) { //成功后的回调
        //        console.log('---3---calculateDistance=', res);
        var res = res.result;
        var dis = [];
        for (var i = 0; i < res.elements.length; i++) {
          var num = res.elements[i].distance / 1000
          var s = num.toFixed(1)
          dis.push(s); //将返回数据存入dis数组，
        }
        _this.setData({ //设置并更新distance数据
          distance: dis
        });

      },
      fail: function (error) {},
      complete: function (res) {}
    });
  },
  //地图视野变化
  regionchange(e) {
    //    console.log(e)
    if (e.detail.type == 'end') {
      this.map_set_center()
    }
  },
  //点击地图时触发，2.9.0起返回经纬度信息
  mapBindtap(e) {
    //    console.log(e, '点击地图时触发，2.9.0起返回经纬度信息')
  }


})